<?php
// 检查文件合法性
function failhandler($tips = '上传失败!'){
    exit("
<script>
    alert('{$tips}')
    location.pathname = '/TeacherStuSys/school/portrait.php'
</script>
");
}

// 空文件
if ($_FILES['img']['size'] == 0) failhandler('不能上传空文件!');
// 文件类型错误
$validTypeArray = ['image/jpeg', 'image/gif', 'image/png'];
if (in_array($_FILES['img']['type'], $validTypeArray) != 1) failhandler('仅能上传 gif、jpg、png 类型的文件!');
// 文件大小
if ($_FILES['img']['size']/1024 > 500) failhandler('仅能上传小于500KB的图片!');

// 连接数据库
include('../inc/data/dbfunc.php');
include('../inc/data/dbparam.php');
$conn = conn_mysql();

// 创建日期文件夹
$nowDate = date('Ymd');
if (file_exists("../inc/portrait/$nowDate") == false) mkdir("../inc/portrait/$nowDate");

// 格式化文件名
$fileName = substr(md5(time() . $_COOKIE['uId']), 0, 16);
// 持久化接受的文件
move_uploaded_file($_FILES['img']['tmp_name'], "../inc/portrait/$nowDate/$fileName");

$defaultImgs = ['te.jpg', 'stu.jpg'];

// 获取用户原头像url
if ($_COOKIE['role'] == 0){
    $sql = "
            select 
                stu_img
            from 
                huangcz_stu
            where
                stu_id = '{$_COOKIE['uId']}'
    ";
}else{
    $sql = "
            select 
                te_img
            from 
                huangcz_te
            where
                te_id = '{$_COOKIE['uId']}'
    ";
}
try {
    $res = $conn->query($sql);
}catch(Exception){
    failhandler();
}
$row = $res->fetch_array();
$rawImgUrl = "../inc/portrait/{$row[0]}";




// 更新数据库img字段
if ($_COOKIE['role'] == 0){
    $sql = "
            update 
                huangcz_stu
            set 
                stu_img = '$nowDate/$fileName'
            where
                stu_id = '{$_COOKIE['uId']}'
    ";
}else{
    $sql = "
            update 
                huangcz_te
            set 
                te_img = '$nowDate/$fileName'
            where
                te_id = '{$_COOKIE['uId']}'
    ";
}

try {
    $res = $conn->query($sql);
}catch(Exception){
    failhandler();
}

if ($row && !in_array($row[0], $defaultImgs)){
    unlink("../inc/portrait/{$row[0]}");
}

session_start();

$iconUrl = "/TeacherStuSys/inc/portrait/$nowDate/$fileName";

$_SESSION['uImg'] = $iconUrl;
session_commit();
setcookie('uImg', $iconUrl, 0, '/TeacherStuSys');

exit("
<script>
    alert('上传成功!')
    location.reload()
</script>
");


